package com.blog.common;

import com.blog.vo.TokenVO;
import com.blog.util.RedisUtil;
import com.blog.util.Result;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * @author tangqj
 * @Description 切面
 * @create 2020/2/18 14:59
 */
@Aspect
@Component
public class ApiAspect {
    @Autowired
    RedisUtil redisUtil;

    @Pointcut("@annotation(com.blog.common.ApiIntercept)")
    private void pointcut() {

    }

    //token校验 部分接口需要验证用户是否还在登陆状态
    @Around("pointcut()&&@annotation(apiIntercept)")
    public void access(ProceedingJoinPoint point, ApiIntercept apiIntercept) throws Throwable {
        Object[] as = point.getArgs();
        Map<String, Object> param = (Map<String, Object>) as[0];
        HttpServletResponse response = (HttpServletResponse) as[1];
        TokenVO tokenVO =  Result.mapToBean(param, TokenVO.class);
        if (StringUtils.isNotEmpty(tokenVO.getLoginUserId()) && StringUtils.isNotEmpty(tokenVO.getToken())) {
            String desc = apiIntercept.desc();
            //表名称
            String tableName = apiIntercept.tableName();
            //进行的操作
            String operation = apiIntercept.operation();
            // 如有需要 查询用户权限,对用户权限进行的细化操作
            Object token = redisUtil.get(tokenVO.getLoginUserId());
            if (tokenVO.getToken().equals(token)) {
                point.proceed();
            } else {
                Result.print(response,Result.responeAjaxMap(false, "token失效,请重新登陆", "", null));
            }
        } else {
            Result.print(response,Result.responeAjaxMap(false, "登陆信息已经过期", "", null));
        }

    }
}
